import {html} from 'htm/preact';
import {isTextFieldEntryEdited, TextAreaEntry} from "@bpmn-io/properties-panel";
import {useService} from "bpmn-js-properties-panel";
import {updateConditionExpression, updateMultiInstance} from "@/components/activiti/util";
import {getBusinessObject} from "bpmn-js/lib/util/ModelUtil";

const component = {
  id: 'conditionExpression',
  component: ConditionExpression
}

if(window['register']) {
  window['register'].regComponent(component.id,component)
}
export default function(element) {
  component['element']=element;
  return component;
}

function getBody(expression) {
  return expression && expression.get('body');
}

function ConditionExpression(props) {
  const { element, id } = props;
  const translate = useService('translate');
  const debounce = useService('debounceInput');
  const bpmnFactory = useService('bpmnFactory');
  const commandStack = useService('commandStack');
  const businessObject = getBusinessObject(element);
  let conditionExpression = businessObject.get('conditionExpression');
  const getValue = () => {
    if(conditionExpression){
      return getBody(conditionExpression) || '';
    }
    return '';
  }

  const setValue = value => {
    return updateConditionExpression(element,conditionExpression,bpmnFactory,commandStack,{
      body: value
    })
  }

  return html`<${TextAreaEntry}
      id=${ element.id+"-ce-"+id }
    element=${ element }
    label=${ translate('ConditionExpression') }
    getValue=${ getValue }
    setValue=${ setValue }
    debounce=${ debounce }
  />`
}

